package com.matrix.async.core;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.matrix.async.service.AsyncTaskService;

public class TaskPackage implements Task {
	private Logger log = Logger.getLogger(TaskPackage.class);
	private static final long serialVersionUID = 1983551720449398895L;

	private transient AsyncTaskService asyncTaskService;
	private final String id;
	private final String name;
	private String taskType = null;

	private List<Task> tasks = new ArrayList<>();

	public TaskPackage(String id, String taskType, AsyncTaskService asyncTaskService) {
		this.id = id;
		this.name = "TaskPackage [" + taskType + "]";
		this.taskType = taskType;
		this.asyncTaskService = asyncTaskService;

	}

	public List<Task> getAllTask() {
		return tasks;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String getTaskType() {
		return taskType;
	}

	@Override
	public void enqueue(QueueEvnet e) {
		for (Task task : tasks) {
			task.enqueue(e);
		}

	}

	@Override
	public void dequeue(QueueEvnet e) {
		for (Task task : tasks) {
			task.dequeue(e);
		}
	}

	@Override
	public void lackOfTask(QueueEvnet e) {

	}

	@Override
	public void fullOfTask(QueueEvnet e) {
	}

	@Override
	public String getID() {
		return id;
	}

	@Override
	public void beforeExecute() {
	}

	@Override
	public boolean execute() {
		return false;
	}

	@Override
	public void afterExecute() {
		backupTaskPackageStatus(id);

	}

	private void backupTaskPackageStatus(String packageId) {
		try {
			asyncTaskService.backupTaskPackage(packageId);
		} catch (Exception e) {
			log.info(e.getMessage(), e);
		}

	}

	@Override
	public boolean retry() {
		return false;
	}

	@Override
	public void onError(Exception e) {
	}

	@Override
	public void setRetryPolicy(RetryPolicy retryPolicy) {
		for (Task task : tasks) {
			task.setRetryPolicy(retryPolicy);
		}
	}

	public void addTask(Task task) {
		tasks.add(task);

	}

}
